package com.susallwave.srcb.serviceimpl.sys;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.susallwave.srcb.dto.PermissionTreeNode;
import com.susallwave.srcb.entity.sys.Permission;
import com.susallwave.srcb.entity.sys.RolePermission;
import com.susallwave.srcb.mapper.sys.PermissionMapper;
import com.susallwave.srcb.mapper.sys.RolePermissionMapper;
import com.susallwave.srcb.response.Result;
import com.susallwave.srcb.response.ResultEnum;
import com.susallwave.srcb.service.sys.PermissionService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author MyBatisPlusGenerator
 * @since 2025-07-20
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    private final RolePermissionMapper rolePermissionMapper;

    @Override
    public Result<IPage<Permission>> page(int pageNum, int pageSize, String code, String name, String status) {
        return null;
    }

    @Override
    public Result<Void> add(Permission permission) {
        Result<Void> repeat = this.isRepeat(permission.getPermissionCode(),permission.getPermissionName());
        if (repeat.getCode()!=200) {
            return repeat;
        }
        this.save(permission);
        return Result.success();
    }

    @Override
    public Result<Void> edit(Permission permission) {
        Result<Void> repeat = this.isRepeat(permission.getPermissionCode(),permission.getPermissionName());
        if (repeat.getCode()!=200) {
            return repeat;
        }
        this.updateById(permission);
        return Result.success();
    }

    @Override
    public Result<Void> isRepeat(String code, String name) {
        if (this.count(new LambdaQueryWrapper<Permission>().eq(Permission::getPermissionCode, code)) != 0) {
            return Result.error(ResultEnum.REPEAT_CODE);
        }
        if (this.count(new LambdaQueryWrapper<Permission>().eq(Permission::getPermissionName, name)) != 0) {
            return Result.error(ResultEnum.REPEAT_NAME);
        }
        return Result.success();
    }

    @Override
    public List<PermissionTreeNode> listPermissionTree() {
        List<Permission> permissions = this.list(new LambdaQueryWrapper<Permission>().orderByAsc(Permission::getOrderNum));
        return buildTree(permissions);
    }

    @Override
    public Map<String, Object> listPermissionTreeByRoleId(Long roleCode) {
        List<PermissionTreeNode> tree = listPermissionTree(); // 已是非递归版本

        List<String> checkedIds = rolePermissionMapper.selectList(
                new LambdaQueryWrapper<RolePermission>().eq(RolePermission::getRoleCode, roleCode)
        ).stream().map(RolePermission::getPermissionCode).collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("tree", tree);
        result.put("checkedKeys", checkedIds);
        return result;
    }
    @Override
    public List<Permission> listByType(String type) {
        return this.list(new LambdaQueryWrapper<Permission>().eq(Permission::getPermissionType, type));
    }

    private List<PermissionTreeNode> buildTreeRecursive(Map<String, List<Permission>> parentMap, String parentCode) {
        List<Permission> children = parentMap.getOrDefault(parentCode, Collections.emptyList());

        // 先排序再构建
        children.sort(Comparator.comparingInt(p -> Optional.ofNullable(p.getOrderNum()).orElse(0)));

        return children.stream().map(permission -> {
            PermissionTreeNode node = BeanUtil.copyProperties(permission, PermissionTreeNode.class);
            node.setChildren(buildTreeRecursive(parentMap, permission.getPermissionCode()));
            return node;
        }).collect(Collectors.toList());
    }


    public List<PermissionTreeNode> buildTree(List<Permission> permissionList) {
        Map<String, PermissionTreeNode> codeNodeMap = new HashMap<>();
        List<PermissionTreeNode> rootNodes = new ArrayList<>();

        // 转换为节点并放入 map
        for (Permission permission : permissionList) {
            PermissionTreeNode node = BeanUtil.copyProperties(permission, PermissionTreeNode.class);
            node.setChildren(new ArrayList<>()); // 初始化避免空指针
            codeNodeMap.put(permission.getPermissionCode(), node);
        }

        // 构建父子关系
        for (Permission permission : permissionList) {
            String parentCode = Optional.ofNullable(permission.getParentCode()).orElse("0");
            PermissionTreeNode currentNode = codeNodeMap.get(permission.getPermissionCode());

            if ("0".equals(parentCode)) {
                rootNodes.add(currentNode);
            } else {
                PermissionTreeNode parentNode = codeNodeMap.get(parentCode);
                if (parentNode != null) {
                    parentNode.getChildren().add(currentNode);
                }
            }
        }

        // 排序函数：按 orderNum 升序排
        Comparator<PermissionTreeNode> orderComparator = Comparator.comparingInt(node -> {
            Integer orderNum = Optional.ofNullable(node.getOrderNum()).orElse(0);
            return orderNum;
        });

        // 对每个子列表递归排序
        sortChildrenRecursively(rootNodes, orderComparator);

        return rootNodes;
    }

    private void sortChildrenRecursively(List<PermissionTreeNode> nodes, Comparator<PermissionTreeNode> comparator) {
        if (CollectionUtils.isNotEmpty(nodes)) return;

        nodes.sort(comparator);
        for (PermissionTreeNode node : nodes) {
            sortChildrenRecursively(node.getChildren(), comparator);
        }
    }

}
